<template>
  <div class="container">
    <nav-bar title="机构详情"></nav-bar>
    <div class="org-info-box">
      <div class="org-img">
        <van-swipe
          class="my-swipe"
          :show-indicators="false"
          :autoplay="2000"
          :lazy-render="true"
          initial-swipe="0"
          indicator-color="white"
        >
          <van-swipe-item v-for="(item, i) in state.imgList" :key="i">
            <img  @click="toView(item)" :src="item" alt="" />
          </van-swipe-item>
        </van-swipe>
      </div>
      <div class="org-infos">
        <div class="org-title">{{ state.detail.name }}</div>
        <ul class="org-items">
          <li>
            <div class="top-title">机构性质</div>
            <div class="value">{{ formatDictCode('JGXZ', state.detail.orgType)  }}</div>
          </li>
          <li>
            <div class="top-title">设立日期</div>
            <div class="value">{{ state.detail.buildDate }}</div>
          </li>
          <li>
            <div class="top-title">占地面积</div>
            <div class="value">{{ state.detail.floorArea }}（m²）</div>
          </li>
          <li>
            <div class="top-title">建筑面积</div>
            <div class="value">{{ state.detail.coveredArea }}（m²）</div>
          </li>
        </ul>
        <div class="contact">
          <div class="contact-item">
            <img src="../../assets/img/view/contact.png" alt="" />
            <span>联系人：涨三</span>
          </div>
          <div class="contact-item">
            <img src="../../assets/img/view/contact-tel.png" alt="" />
            <span>联系电话：19877667766</span>
          </div>
        </div>
      </div>
    </div>
    <div class="org-position-box">
      <div class="title-box">位置信息</div>
      <map-view
        class="map"
        :key="keyValue"
        @getDistance="getDistance"
        :latitude="state.detail.latitude"
        :longitude="state.detail.longitude"
      ></map-view>
      <div class="position-text">
        <div class="text-box">
          <div class="text">
            {{ state.detail.inArea }}{{ state.detail.belongArea }}
          </div>
          <van-button plain type="primary" round @click="toGo">导航</van-button>
        </div>
        <div class="text-box2" v-if="distance">
          距您{{ distance.toFixed(2) }}公里
        </div>
      </div>
    </div>
    <div class="org-other-box">
      <van-tabs
        class="tab"
        color="#4E86F6"
        style="height: 100%"
        background="#ffffff00"
        title-active-color="#000000"
        title-inactive-color="#AAABAD"
        v-model:active="active"
        swipeable
        @change="changeTabs"
      >
        <van-tab
          style="height: 100%"
          v-for="(item, i) in state.tabList"
          :title="item.title"
          :key="i"
        >
          <div class="tab-content">
            <component
              :is="CurrentComponent[activePage]"
              :currentDetail="state.detail"
            />
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  provide,
  onBeforeMount,
  markRaw,
  defineAsyncComponent
} from 'vue'
import { formatDictCode } from '@/utils/format.js'
import { useUserStore } from '@/pinia/modules/user'
import { appCurrentState } from '@/pinia/modules/app.js'
import { get_detail } from '@/api/api'
import { showImagePreview } from "vant";
import mapView from './components/map.vue'

const CurrentComponent = reactive({
  orgInfos: markRaw(
    defineAsyncComponent(() => import('./components/org-infos.vue'))
  ),
  oldManType: markRaw(
    defineAsyncComponent(() => import('./components/old-man-type.vue'))
  ),
  orgType: markRaw(
    defineAsyncComponent(() => import('./components/org-type.vue'))
  )
})
const activePage = ref('orgInfos')
const currentDetail = ref({})
const userStore = useUserStore()
const defaultImgUrl = ref(
  new URL('../../assets/img/common/waitImg.png', import.meta.url).href
)
const active = ref('机构简介')
const keyValue = ref('')
const distance = ref()
const state = reactive({
  tabList: [
    {
      title: '机构简介',
      path: 'orgInfos'
    },
    {
      title: '收住老人类型',
      path: 'oldManType'
    },
    {
      title: '机构特征',
      path: 'orgType'
    }
  ],
  detail: {},
  imgList: [],
  imgList2: []
})

const getDistance = val => {
  console.log(val)
  distance.value = val
}

const changeTabs = i => {
  activePage.value = state.tabList[i].path
}

const toView = (val) => {
      let i = state.imgList.findIndex((item) => {
        return item == val;
      });
      showImagePreview({
        images: state.imgList,
        startPosition: i
      });
    }

const timedGetText = url => {
  return new Promise((resolve, reject) => {
    var request = new XMLHttpRequest()
    request.open('GET', url)
    request.setRequestHeader('Authorization', userStore.token)
    request.onreadystatechange = function () {
      if (request.readyState !== 4) return
      if (request.status === 200) {
        resolve(JSON.parse(request.responseText))
      }
    }
    request.send()
  })
}

const getImgBase64 = async () => {
  for (let i = 0; i < state.imgList2.length; i++) {
    let res = await timedGetText(
      userStore.fileUrl + '/download_base64/' + state.imgList2[i]
    )
    if (res) {
      state.imgList.push('data:image/jpg;base64,' + res.data.dataBase64)
    }
  }
}

const isNull = arr => {
  let newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]) {
      newArr.push(arr[i])
    }
  }
  return newArr
}

const toGo = () => {
  window.location.href = `https://uri.amap.com/marker?position=${state.detail.longitude},${state.detail.latitude}&name=${state.detail.name}&src=mypage&coordinate=gaode&callnative=1`
}

const getDetail = async () => {
  let res = await get_detail(
    appCurrentState().getCurrentDetailId,
    '/gov-portal/org'
  )
  if (res.succeed) {
    state.detail = res.data
    state.imgList2 = isNull(
      (res.data.headImage + res.data.enviromentImage).split(',')
    )
    // state.imgList2 = state.imgList2.filter(function (s) {
    //   return s && s.trim() // 注：IE9(不包含IE9)以下的版本没有trim()方法
    // })
    await getImgBase64()
  }
}

onBeforeMount(() => {
  getDetail()
})
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  .org-info-box {
    background-color: #fff;
    padding: 36px 0 10px 0;
    .org-img {
      width: calc(100% - 72px);
      margin: 0 auto 36px auto;
      .my-swipe {
        height: 400px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .org-infos {
      width: calc(100% - 72px);
      margin: 36px auto 0 auto;
      .org-title {
        font-size: 48px;
        font-weight: bold;
        margin: 40px 0 20px 0;
        color: #333333;
      }
      .org-items {
        display: flex;
        align-items: center;
        justify-content: space-around;
        border: 2px solid #f3f3f3;
        li {
          flex: 1;
          text-align: center;
          &:nth-child(2) {
            border-left: 2px solid #f3f3f3;
            border-right: 2px solid #f3f3f3;
          }
          &:nth-child(4) {
            border-left: 2px solid #f3f3f3;
          }
          .top-title {
            margin: 10px 0;
            font-size: 34px;
            font-weight: 500;
            color: #333333;
          }
          .value {
            margin: 10px 0;
            font-size: 26px;
            font-weight: 500;
            color: #999999;
          }
        }
      }
      .contact {
        margin: 20px 0;
        display: flex;
        align-items: center;
        .contact-item {
          display: flex;
          align-items: center;
          font-size: 30px;
          font-weight: 500;
          color: #333333;
          &:nth-child(1) {
            width: 38%;
          }
          &:nth-child(2) {
            width: 62%;
            margin-left: 40px;
          }
          span {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          img {
            margin-right: 10px;
            width: 30px;
            height: 30px;
          }
        }
      }
    }
  }
  .org-position-box {
    background-color: #fff;
    margin: 30px 0;
    padding: 20px 0;
    .title-box {
      width: calc(100% - 72px);
      margin: 20px auto;
      font-size: 48px;
      font-weight: bold;
      color: #333333;
    }
    .map {
      width: calc(100% - 72px);
      margin: 0px auto;
    }
    .position-text {
      .text-box {
        width: calc(100% - 72px);
        display: flex;
        align-items: center;
        margin: 20px auto 0 auto;
        .text {
          font-size: 32px;
          color: #333333;
          margin-right: 10px;
          white-space: nowrap;
          max-width: calc(100% - 160px);
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .text-box2 {
        width: calc(100% - 72px);
        margin: 0px auto;
        font-size: 32px;
        color: #4e86f6;
      }
    }
  }
  .org-other-box {
    background-color: #fff;
    margin: 30px 0;
    padding: 20px 0;
    .tab {
      width: 100%;
      margin: 0px auto;
      .tab-content {
        width: calc(100% - 72px);
        margin: 0px auto;
      }
    }
  }
}
:deep(.van-tab) {
  transition: 400ms;
  font-size: 32px;
  line-height: 85px;
}
:deep(.van-tab--active) {
  font-size: 48px;
}
:deep(.van-tab__text--ellipsis) {
  display: block;
  height: 100%;
}
:deep(.van-tabs__line) {
  width: 64px;
  height: 12px;
}
:deep(.van-tab__panel) {
  height: 100%;
}
:deep(.van-tabs__content) {
  height: calc(100% - 120px);
}
:deep(.van-tabs__nav) {
  .van-tab {
    &:nth-child(2) {
      flex: 1.4;
    }
  }
}
:deep(.van-button--normal) {
  padding: 10px 25px;
  height: 50px;
}
</style>
